package cn.bdqn.controller;

import cn.bdqn.bean.Role;
import cn.bdqn.bean.User;
import cn.bdqn.service.RoleService;
import cn.bdqn.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String login(String userCode, String userPassword, Model model, HttpSession session) {
        User user = userService.login(userCode, userPassword);
        if (user != null) {
            // 跳转到欢迎页面
            session.setAttribute("CURRENT_USER", user);
            return "frame";
        } else {
            model.addAttribute("error", "用户名或密码错误！");
            return "forward:/login.jsp";
        }
    }
    // @ControllerAdvice + @ExceptionHandler
//    @ExceptionHandler(value = ArithmeticException.class)
//    public String handlerException(ArithmeticException e,HttpServletRequest request){
//        request.setAttribute("exception",e);
//        return "error";
//    }

    @RequestMapping("/list.html")
    public String list(@RequestParam(value = "pageIndex",
            required = false, defaultValue = "1") Integer pageIndex,
                       Model model, User user) {
        PageHelper.startPage(pageIndex, 4);
        List<User> users = userService.getUsersSelective(user);
        PageInfo<User> pageInfo = new PageInfo<>(users);

        // 查询出所有的用户角色
        List<Role> roles = roleService.getRoles();
        model.addAttribute("roles", roles);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("user", user);
        return "test/userlist";
    }

    @RequestMapping("/add")
    public String gotoUserAdd(Model model) {
        List<Role> roles = roleService.getRoles();
        model.addAttribute("roles", roles);
        return "useradd";
    }

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public String saveUser(User user,
                           @RequestParam(value = "idFile", required = false)
                                   MultipartFile[] multipartFiles, HttpServletRequest request) {
        if (multipartFiles != null) {
            for (int i = 0; i < multipartFiles.length; i++) {
                // 上传
                // 保存路径
                String path = request.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
                // 获取上传文件的名
                String oldFileName = multipartFiles[i].getOriginalFilename();
                // 获取上传文件的扩展名
                String suffix = FilenameUtils.getExtension(oldFileName);
                // 允许上传文件大小
                int fileSIze = 500000;
                if (multipartFiles[i].getSize() > fileSIze) {
                    request.setAttribute("uploadFileError", "上传文件不得超过500kb");
                    return "forward:/user/add";
                } else if (suffix.equalsIgnoreCase("jpg")
                        || suffix.equalsIgnoreCase("png")
                        || suffix.equalsIgnoreCase("jpeg")
                        || suffix.equalsIgnoreCase("pneg")) {
                    // 生成新的文件名
                    String fileName = oldFileName + "_" + System.currentTimeMillis() + "." + suffix;
                    // 空白文件
                    File file = new File(path, fileName);
                    // 判断此文件路径是否存在
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    // 从multipartFile取出上传文件内容，然后传输到空白文件中
                    try {
                        multipartFiles[i].transferTo(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (i == 0){
                        user.setIdPicPath("/statics/uploadfiles/" + fileName);
                    }else{
                        user.setWorkPicPath("/statics/uploadfiles/" + fileName);
                    }
                } else {
                    // 图片格式不正确
                    request.setAttribute("uploadFileError", "上传图片格式不正确");
                    return "forward:/user/add";
                }
            }

        }
        int rs = userService.addUser(user);
        if (rs > 0) {
            return "redirect:/user/list";
        } else {
            return "redirect:/user/add";
        }
    }

    @RequestMapping("/check")
    @ResponseBody
    public String checkCode(User user) {
        Map<String,String> data = new HashMap<>();
        List<User> users = userService.getUsersSelective(user);
        if (users != null && !users.isEmpty()){
            // 用户名重复
            data.put("userCode","exists");
        }else{
            // 用户名不重复
            data.put("userCode","notExists");
        }
        String json = JSON.toJSONString(data);
        return json;
    }

    @RequestMapping("/modify")
    public String gotoModifyPage(Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        // 查询出所有的用户角色
        List<Role> roles = roleService.getRoles();
        model.addAttribute("roles", roles);
        return "usermodify";
    }

    @RequestMapping(value = "/users/1", method = RequestMethod.PUT)
    public String update(User user) {
        int rs = userService.updateUser(user);
        if (rs > 0) {
            return "redirect:/user/list";
        } else {
            return "redirect:/user/modify";
        }
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public String gotoViewPage(@PathVariable("id") Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "userview";
    }

    @RequestMapping(value = "/json.json")
    @ResponseBody
    public Object getUser(Integer id){
        User user = userService.getUserById(id);
        return user;
    }

    @InitBinder
    public void initBinder(WebDataBinder dataBinder){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
    }


}
